package com.example.je_0309;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getc")
    public String getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        }
        return  "获取cookie成功";
    }


    @RequestMapping("/getc2")
    public String getCookie(@CookieValue(value = "spring") String spring) {
        return "从Cookie中获取值 spring：" + spring;
    }



    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        return "设置成功";
    }

    @RequestMapping("/getSess1")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取 name："  + name;
    }

    @RequestMapping("/getSess2")
    public String getSession2(HttpSession session) {
        String name = (String) session.getAttribute("name");
        return "从session中获取 name："  + name;
    }

    @RequestMapping("/getSess3")
    public String getSession3(@SessionAttribute(value = "name") String name) {
        return "从session中获取 name："  + name;
    }


    @RequestMapping("/getHeader1")
    public String getHeader1(HttpServletRequest request) {

        //大小写不敏感
        String userAgent = request.getHeader("user-agent");
        return "从Header中获取 userAgent："  + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("user-agent") String userAgent) {
        return "从Header中获取 userAgent："  + userAgent;
    }

}
